package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.StorageClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class FileController {

    //缺啥补啥

    /***
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        try {

            //3.补齐相关的参数
            //文件名称
            String originalFilename = file.getOriginalFilename();
            //文件内容
            byte[] bytes = file.getBytes();
            //文件名扩展 123.456.png--->png
            String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);

            //2.构建FastDFSFile
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, ext);

            //1.使用工具类上传文件
            String[] upload = FastDFSClient.upload(fastDFSFile);
            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];

            //4.构建返回体
            return new Result(true, StatusCode.OK, "文件上传成功", url);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }

    @GetMapping("/downLoad")
    public Result downLoad(@RequestParam Map map) {
        try {

            //3.补齐参数
            String groupName = (String) map.get("groupName");
            String remoteFileName = (String) map.get("remoteFileName");

            //2.构建
            FileInfo fileInfo = FastDFSClient.getFile(groupName, remoteFileName);
            long crc32 = fileInfo.getCrc32();
            long fileSize = fileInfo.getFileSize();
            String sourceIpAddr = fileInfo.getSourceIpAddr();
            String toString = fileInfo.toString();

            //1.使用工具类下载文件
            InputStream downLoadFile = FastDFSClient.downFile(groupName, remoteFileName);
            return new Result(true, StatusCode.OK, "文件下载成功",downLoadFile);
        } catch (Exception e) {

        }
        return new Result(false, StatusCode.ERROR, "文件下载失败");
    }

    @DeleteMapping("/delete")
    public Result delete(@RequestParam Map map) {
        try {

            //3.补齐相关参数
            String groupName = (String) map.get("groupName");
            String remoteFileName = (String) map.get("remoteFileName");

            //2.构建
            FileInfo fileInfo = FastDFSClient.getFile(groupName, remoteFileName);

            //1.使用工具类删除文件
            FastDFSClient.deleteFile(groupName, remoteFileName);
            return new Result(true, StatusCode.OK, "删除文件成功");
        } catch (Exception e) {

        }
        return new Result(false, StatusCode.ERROR, "删除文件失败");
    }
}
